<?php
namespace app\wechat\home;
use app\common\controller\Common;

/**
 * 微信公从号消息回调入口
 * @author King
 *
 */
class Callback extends Common
{
    public function index()
    {
    	try {
    		$wechat = \We::WeChatReceive(config('wechat.'));

    		// 获取当前推送接口类型 ( text,image,loction,event... )
    		$msgType = $wechat->getMsgType();

    		// 获取当前推送来源用户的openid
    		$openid = $wechat->getOpenid();

    		// 获取当前推送的所有数据
    		$data = $wechat->getReceive();

    		switch ($msgType) {
    			case 'text':
    				return controller('wechat/Text', 'home')->index($wechat, $data);
    				break;
    			case 'image':
    				break;
    			case 'voice':
    				break;
    			case 'video':
    				break;
    			case 'location':
    				break;
    			case 'link':
    				break;
    			case 'event':
    				return $this->_doEvent($wechat, $data);
    				break;
    			default:
    				throw new \Exception('unkown msgType '.$msgType);
    		}

    		$content = "消息类型:{$msgType}，openid:{$openid}，消息内容：".json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    		$wechat->text($content)->reply();
    	} catch (\Exception $e) {
    		addLog($e->getMessage(), 'wechat_error');
    	}
    }

    /**
     * 事件处理
     *
     * @author King
     * @date 2020年8月13日
     *
     * @param \WeChat\Receive $wechat
     * @param array $data
     * @return mix
     */
    private function _doEvent($wechat, $data) {
    	$event = arrayGet($data, 'Event');
    	switch ($event) {
    		case 'subscribe':	// 关注/扫描带参数二维码事件且用户未关注
    			return controller('wechat/EventSubscribe', 'home')->index($wechat, $data);
    			break;
    		case 'SCAN':	// 扫描带参数二维码事件且用户已关注
    			break;
    		case 'unsubscribe':	// 取消关注
    			return controller('wechat/EventUnsubscribe', 'home')->index($wechat, $data);
    			break;
    		case 'LOCATION':	// 上报地理位置
    			break;
    		case 'CLICK':	// 点击菜单拉取消息的事件推送
    			break;
    		case 'VIEW':	// 点击菜单跳转链接的事件推送
    			break;
    		default:
    			throw new \Exception('unkown event '. $event);
    	}

    	$content = "事件消息内容：".json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    	$wechat->text($content)->reply();
    }
}